package com.bc.utils.network;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;

public class HttpRequestClient {
	private static final int DEFAULT_MAX_CONNECTIONS = 10;
	private static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000;
	private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
	public static final String BOUNDARY = "7cd4a6d158c";
	public static final String MP_BOUNDARY = "--" + BOUNDARY;
	public static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--";

	private static DefaultHttpClient httpClient;
	private static HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());

	static {
		BasicHttpParams httpParams = new BasicHttpParams();

		ConnManagerParams.setTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
		ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

		HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		HttpConnectionParams.setTcpNoDelay(httpParams, true);
		HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

		HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setUserAgent(httpParams, "yunlai");

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

		httpClient = new DefaultHttpClient(cm, httpParams);

	}

	public static String get(String url) throws ClientProtocolException, IOException {
		HttpUriRequest httpRequest = new HttpGet(url);
		HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);
		StatusLine status = httpResponse.getStatusLine();
		String responseBody = null;
		HttpEntity entity = null;
		HttpEntity temp = httpResponse.getEntity();
		if (temp != null) {
			entity = new BufferedHttpEntity(temp);
			responseBody = EntityUtils.toString(entity, "UTF-8");
		}

		if (status.getStatusCode() >= 300) {
			throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
		}
		return responseBody;
	}
	
	/**
	 * POST方式请求数据
	 * @param url
	 * @param paramArrayOfByte 请求数据
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String post(String url,byte[] paramArrayOfByte)throws ClientProtocolException, IOException{
		HttpPost httpRequest = new HttpPost(url);
		ByteArrayEntity arrayEntity=new ByteArrayEntity(paramArrayOfByte);
		arrayEntity.setContentType("application/octet-stream");
		httpRequest.setEntity(arrayEntity);
		
		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpRequest, httpContext);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
		StatusLine status = httpResponse.getStatusLine();
		String responseBody = null;
		HttpEntity entity = null;
		
		HttpEntity temp = httpResponse.getEntity();
		if (temp != null) {
			entity = new BufferedHttpEntity(temp);
			responseBody = EntityUtils.toString(entity, "UTF-8");
		}

		if (status.getStatusCode() >= 300) {
			throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
		}
		return responseBody;
	}
	
	/**
	 * 图片上传
	 * @param out
	 * @param imgBitmap
	 */
	public static void imageContentToUpload(OutputStream out, Bitmap imgBitmap)
           {
        StringBuilder temp = new StringBuilder();

        temp.append(MP_BOUNDARY).append("\r\n");
        temp.append("Content-Disposition: form-data; name=\"pic\"; ").append("filename=\"headImage.png\"").append("\r\n");
        temp.append("Content-Type: ").append("image/png").append("\r\n\r\n");
        byte[] res = temp.toString().getBytes();
        
        try {
            out.write(res);
            imgBitmap.compress(CompressFormat.PNG, 100, out);
            out.write("\r\n".getBytes());
            out.write(("\r\n" + END_MP_BOUNDARY).getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            
        }
    }
}
